package com.fin.zw.intelligentbot.service;


import com.fin.zw.intelligentbot.entity.*;
import com.fin.zw.intelligentbot.enums.UserStatus;
import com.fin.zw.intelligentbot.model.request.UserInfoRequest;
import com.fin.zw.intelligentbot.model.response.UserInfoResponse;
import com.fin.zw.intelligentbot.model.session.SessionModel;
import com.fin.zw.intelligentbot.repository.AccountRepository;
import com.fin.zw.intelligentbot.repository.RoleInfoRepository;
import com.fin.zw.intelligentbot.repository.UserInfoRepository;
import com.google.common.collect.Lists;
import com.querydsl.core.BooleanBuilder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;


@Service("userInfoService")
public class UserInfoService {
    private static final Logger log = LoggerFactory.getLogger(UserInfoService.class);

    @Autowired
    private UserInfoRepository userInfoRepository;

    @Autowired
    private AccountRepository accountRepository;

    @Autowired
    private RoleInfoRepository roleInfoRepository;

    @Autowired
    private CommonService commonService;

    /**
     * 用户的创建
     * @param request
     */
    @Transactional
    public void createUserInfo(UserInfoRequest request, SessionModel sessionModel) {
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(request,userInfo);
        if (StringUtils.isNotEmpty(sessionModel.getCompanyId())) {
            userInfo.setCompany(commonService.getCompany(sessionModel));
        } else {
            userInfo.setCompany(request.getCompany());
        }
        Account account = createAccount(request);
        userInfo.setAccount(account);

        userInfoRepository.save(userInfo);
    }

    /**
     * 创建账号
     * @param request
     */
    public Account createAccount(UserInfoRequest request) {
        Iterator<Account> iterator = accountRepository.findAll(QAccount.account.name.eq(request.getAccountName())).iterator();
        if(iterator.hasNext()){
            throw new RuntimeException("该账号已经被占用...");
        }
        Account account = new Account();
        account.setName(request.getAccountName());
        account.setUserStatus(UserStatus.USER_START);
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String pwd = passwordEncoder.encode("zhiwang");
        account.setPassword(pwd);
        if (request.getRoleIds() != null && !request.getRoleIds().isEmpty()) {
            Iterator<RoleInfo> infoIterator = roleInfoRepository.findAll(QRoleInfo.roleInfo.id.in(request.getRoleIds())).iterator();
            Set<RoleInfo> set = new HashSet<>(Lists.newArrayList(infoIterator));
            account.setRoleInfoSet(set);
        }
        account = accountRepository.save(account);
        return account;
    }

    /**
     * 用户信息的更新
     * @param request
     */
    public void updateUserInfo(UserInfoRequest request){
        UserInfo userInfo = userInfoRepository.findById(request.getId()).orElseThrow(()->new RuntimeException("用户信息不存在"));
        Account account = userInfo.getAccount();
        if (request.getRoleIds() != null && !request.getRoleIds().isEmpty()) {
            Iterator<RoleInfo> infoIterator = roleInfoRepository.findAll(QRoleInfo.roleInfo.id.in(request.getRoleIds())).iterator();
            Set<RoleInfo> set = new HashSet<>(Lists.newArrayList(infoIterator));
            account.setRoleInfoSet(set);
        }
        accountRepository.save(account);
        userInfo.setName(request.getName());
        userInfo.setStatus(request.getStatus());
        userInfo.setPhone(request.getPhone());
        userInfo.setSex(request.getSex());
        userInfo.setCompany(request.getCompany());
        userInfo.setAccount(account);
        userInfoRepository.save(userInfo);
    }


        /**
     * 查询用户信息（分页）
     * @param pageable
     * @return
     */
    public Page<UserInfoResponse> getUserInfoAll(UserInfoRequest request, Pageable pageable, SessionModel sessionModel){
        BooleanBuilder builder = new BooleanBuilder();
        QUserInfo qUserInfo = QUserInfo.userInfo;
        if(Objects.isNull(sessionModel.getCompanyId())){
            if(request.getCompany() != null){
                builder.and(qUserInfo.company.id.eq(request.getCompany().getId()));
            }
        }else{
            builder.and(qUserInfo.company.id.eq(sessionModel.getCompanyId()));
        }
        if(StringUtils.isNotEmpty(request.getName())){
            builder.and(qUserInfo.name.like("%".concat(request.getName()).concat("%")));
        }
        if(StringUtils.isNotEmpty(request.getPhone())){
            builder.and(qUserInfo.phone.eq(request.getPhone()));
        }
        Page<UserInfo> userInfoPage = userInfoRepository.findAll(builder,pageable);
        Page<UserInfoResponse> page = userInfoPage.map(userInfo -> {
            UserInfoResponse response = new UserInfoResponse();
            BeanUtils.copyProperties(userInfo, response);
            if(Objects.nonNull(userInfo.getAccount())) {
                Account account = userInfo.getAccount();
                response.setAccountId(account.getId());
                response.setAccountName(account.getName());
                response.setAccountStatus(account.getUserStatus());
                response.setRoleInfoSet(account.getRoleInfoSet());
            }
            return response;
        });
        return page;
    }
}
